package com.demon.mutehelper

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.util.Log
import androidx.activity.result.ActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.lifecycleScope
import com.afollestad.materialdialogs.MaterialDialog
import com.afollestad.materialdialogs.datetime.dateTimePicker
import com.demon.mutehelper.application.CustomApp
import com.demon.mutehelper.databinding.ActivityMuteRecordEditBinding
import com.demon.mutehelper.viewmodel.MuteRecordEditViewModel
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch

class MuteRecordEditActivity : AppCompatActivity() {

  private val mRecordId: Int by lazy { intent.getIntExtra(BUNDLE_KEY_RECORD_ID, -1) }
  private val mViewModel: MuteRecordEditViewModel by viewModels {
    MuteRecordEditViewModel.MuteRecordEditViewModelFactory(
      CustomApp.instance,
      mRecordId
    )
  }
  private lateinit var mBinding: ActivityMuteRecordEditBinding
  private val locationChooseLauncher =
    registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { activityResult ->
      activityResult?.resultCode?.takeIf { resultCode -> resultCode == RESULT_OK }.let {
        activityResult.data?.getSerializableExtra(MapActivity.RESULT_BUNDLE_KEY_MAP_CHOSEN)
          ?.run { this as MapActivity.MapChosenBean }?.apply {
            mViewModel.updateLocation(name, lat, lon)
          }

      }
    }

  override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    mBinding = DataBindingUtil.setContentView(
      this,
      R.layout.activity_mute_record_edit
    )
    mBinding.clickHandler = ClickHandler()
    mBinding.viewModel = mViewModel
    initToolbar()
    subscribeUI()
  }

  private fun initToolbar() {
    mBinding.toolBar.apply {
      if (mRecordId > 0) {
        inflateMenu(R.menu.toolbar_menu_edit)
        setOnMenuItemClickListener {
          when (it.itemId) {
            R.id.action_delete -> {
              mViewModel.delete()
            }
          }
          true
        }
      }
    }
  }

  private fun subscribeUI() {
    lifecycleScope.launch {
      mViewModel.uiStateFlow.collectLatest {
        it.takeIf { it == MuteRecordEditViewModel.UIState.Success }.run { finish() }
      }
    }

  }

  inner class ClickHandler {
    fun onLocationClicked() {
      locationChooseLauncher.launch(Intent(this@MuteRecordEditActivity, MapActivity::class.java))
    }

    fun onTimeClicked() {
      MaterialDialog(this@MuteRecordEditActivity).show {
        dateTimePicker(show24HoursView = true) { dialog, datetime ->
          mViewModel.updateStartTime(
            datetime.timeInMillis
          )
        }
      }
    }
  }

  companion object {
    private const val BUNDLE_KEY_RECORD_ID = "BUNDLE_KEY_RECORD_ID"
    fun makeIntent(context: Context, recordId: Int? = null): Intent {
      return Intent(context, MuteRecordEditActivity::class.java).apply {
        recordId?.let { id -> putExtra(BUNDLE_KEY_RECORD_ID, id) }
      }
    }
  }
}